# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""CLI for demo.
Usage:
  CLI.py 

e.g:
- q 退出
- h 帮助
- 逐行输入
- 实时记录为文件
- 再次打开时回放过往所有笔记
"""

import sys
import time
import os.path

import requests
from config import CFG
from xsettings import XCFG

CRT_PS1 = CFG.PS0
def diary( api_root ):
    global CRT_PS1
    print("Historic Diary:")
    print _list4tag(_sync_his(api_root))
    #_his = _sync_his(api_root)
    #print type(_his)
    #print _his.keys()
    #print _his['logs']

    print("Diary now...")
    while 1:
        d = raw_input(CRT_PS1)
        #print d[:3]
        if d in ['?','h','H','help']:
            print('''是也乎,(￣▽￣)
            >>> ?/h/H 打印当前帮助
            >>> q/bye 退出笔记
            >>> s/sync 同步笔记
            >>> lt/ListTags 标签清单
            >>> st:TAG 设定|清除 标签
            >>> FLUSH 清空所有!重新来!
            >>> e:MSG 微信测试
                e:? 公众号帮助
                e:s 公众号笔记回放
                e:V 公众号版本
                e:m..笔记在公众号

            by {}
                '''.format(CFG.VERSION)
                )


        elif d in ['q','quit','bye']:
            break
        elif d in ['s','sync']:
            #logs = _sync_his(api_root)
            #print type(logs)
            if CRT_PS1 == CFG.PS0:
                # default tag
                ctag = CFG.TAG0
            else:
                ctag = CRT_PS1.split('<<<')[0]
            print _list4tag(_sync_his(api_root), tag=ctag)
        elif 'e:' == d[:2]:
            toUser = XCFG.AS_SRV
            fromUser = XCFG.AS_USR
            tStamp = int(time.time())
            content = d[2:]#.split(":")[1].strip()
            xml = CFG.TPL_TEXT % locals()
            #cmd = "curl -d '%s' %s/%s "% (xml, AS_LOCAL, 'echo')
            r = requests.post(XCFG.DEV2wx, data=xml)
            print r.text



        elif 'FLUSH' == d or 'FF' == d:
            print 'restart as EMPTY !-)'
            payload = {'log': "FLUSH"}
            r = requests.post(api_root, data=payload)
            #print r.text
        elif d in ['lt']:
            r = requests.get("%s/lt"%api_root)
            print r.text


        elif 'st:' == d[:3]:
            if 'st:' == d:
                CRT_PS1 = CFG.PS0
            else:
                CRT_PS1 = "%s<<< "%d[3:]
        else:
            if ">>>" in CRT_PS1:
                # tag as NULL/default
                _ps1 = CFG.TAG0
            else:
                _ps1 = CRT_PS1.split('<<<')[0]
            payload = {'log': "{}{}{}".format(_ps1,CFG.GAP0,d) }
            #print payload
            if 0 == len(d):
                pass
            else:
                r = requests.put(api_root, data=payload)
                #print r.text


    print("亲, bye ~")

def _list4tag(logs, tag='NULL'):
    print 'TAG as:',tag
    _exp = ""
    for l in logs:
        #print l.split(CFG.GAP0)
        if l:
            if CFG.GAP0 in l:
                ctag, msg = l.split(CFG.GAP0)
                if ctag == tag:
                    _exp += msg+'\n'
            
    return _exp
def _sync_his(api_root):
    uri = api_root
    #print uri
    r = requests.get(uri)
    #return r.text
    return r.json()['logs']

if __name__ == '__main__':
    if 2 != len(sys.argv) :
        print('''Usage:
        $ python CLI.py -[D|U]
                          | +- User
                          +- Debugging
                ''')
    else:
        if 'D' in sys.argv[1]:
            diary(XCFG.TO_DEV)
        else:
            diary(XCFG.TO_SAE)
        #diary()
